<?php

/**
 * Page de récupération de mot de passe, peut recevoir en paramètre POST l'adresse mail de demande
 * @version 20071005
 * @author Antoine Marcadet
 */

require('config.php');
if(isset($_SESSION['URL_BACK'])){
    header('location:'.$_SESSION['URL_BACK'].'&send');
}
//Vérifier que l'utilisateur est connecté
elseif(isset($_SESSION['id_user'])&&!isTranslating()) {
    redirectFront('index');
}

$page = new rootLayoutPage();
$page->setBaliseTitle('ouli_balise');
$page->setDescription('oubli_description');
//-- menu Left show products--------------------------------//
/*$menu = new layoutMenu();
$menuCategorie = new layoutMenuCategorie();
$menu->pushMenu($menuCategorie);
$menuPage = new layoutMenuPage();
$menu->pushMenu($menuPage);
$page->setMenu($menu);*/

//--------Menu indicator--------------//
/*$menuIndictor = new layoutMenuIndicator();
	$menuIndictor->title('Forgot password');
	$page->setMenuIndicator($menuIndictor);
*/
//-- corps de la page --------------------------------------------------------//
$xml = tmxTranslate('oubli.xml', REP_XLAT_TEMPLATE);
$xml_subject = tmxTranslate('subject.mail.xml', REP_XLAT_MAIL);
$tpl_file='oubli.tpl';
$oubli = new flyLayout(REP_TPL . $tpl_file);
$oubli->start();

if(isset($_GET['id']) and isset($_GET['clef'])) { // arrivée par lien mail
    $id_user = normalise($_GET['id'], 'int');
    $key_unique = normalise($_GET['clef'], 'int');
    $user = modelUser::getUserIdKeyUnique($id_user, $key_unique);
    if($user) {
        if(isset($_POST['password']) and isset($_POST['confirm'])) { // modification du mot de passe
            $password = addslashes($_POST['password']);
            $confirm  = addslashes($_POST['confirm']);
            if(($password != '' or $confirm != '') and $password == $confirm) {
            	$key_unique_new = time().rand(10000000, 99999999);
                modelUser::updatePass($user->id_user, $password);// DEBUT envoi du mail
                modelUser::updateKeyUnique($user->id_user,$key_unique_new);
                modelUser::connexion($user->login, $password);
                $oubli->setVariable('http_host', HTTP_HOST);
                $oubli->showBlock('confirmation_password');
            }
            else {
            	Persistence::register(PERSIST_MESSAGE, new Message($xml['error_message_6'], Message::ERROR));
                //echo 'vos deux mots de passe doivent etre identiques et différents de vide';
                $oubli->showBlock('password');
            }
        }
        else {
            if($user->etat_user == modelUser::EMAIL_VALIDE) {
                $oubli->showBlock('password');
            }
            else {
                // si le compte est deja activé le lien ne doit plus marcher !!!!!!
                Persistence::register(PERSIST_MESSAGE, new Message($xml['error_message_5'], Message::ERROR));
                //echo 'Vous ne pouvez pas redemander le mot de passe d\'un compte pas encore activé';
            }
        }
    }
    else {
    	Persistence::register(PERSIST_MESSAGE, new Message($xml['error_message_4'], Message::ERROR));
        //echo 'Problème de cohérence dans l\'adresse saisie, merci de recopier correctement le lien, un mail a été envoyé a l\'administrateur';
    }
}
else if(isset($_POST['mail_oubli']) and trim($_POST['mail_oubli']) != '') { // récupération du mot de passe
    $email = $_POST['mail_oubli'];
    if(isValidEmail($email)) {
        $user = modelUser::getUserMail($email);
        if($user) { // le compte utilisateur existe
            if($user->etat_user == modelUser::EMAIL_VALIDE) {

				$tpl_file = 'oublimdp.mail.tpl';
				$mail = new flyLayout(REP_MAIL . $tpl_file);
            	$mail->start();

                $mail->setVariable('lien_activation', HTTP_HOST.'oubli.php?id='.$user->id_user.'&clef='.$user->key_unique);
            	$mail->stop();
            	$destinataire = $email;
            	$subject = $xml_subject['oublimdp'].' '.MAIL_SITENAME;
            	if(STATUS_EMAIL == 0) {
	        		echo $mail;
	        	}elseif(STATUS_EMAIL == 1) {
	        		monsterMail($destinataire, $subject, $mail);
	        	}else {
	        		echo $mail;
	        		monsterMail($destinataire, $subject, $mail);
	        	}

                $oubli->showBlock('confirmation');
            }else {
            	$mail = new flyLayout(REP_MAIL.'inscription.mail.tpl');
					$mail->start();
					$mail->setVariable('mail_utilisateur', $email);
					$mail->setVariable('lien_activation', 'http://'.$_SERVER['HTTP_HOST'].LANGUAGE_FOLDER.'/validation.php?id='.$user->id_user.'&clef='.$user->key_unique);
					$mail->stop();

					$subject = $xml_subject['resend_mail_validation'];
					$email_mail = $email;
					if(!$_SESSION['user_not_validate']){
	        		$arr = array($login => time());
	        		$_SESSION['user_not_validate'] = $arr;
		        		if(STATUS_EMAIL == 0) {
		        			echo $mail;
			        	}elseif(STATUS_EMAIL == 1) {
			        		monsterMail($email_mail, $subject, $mail);
			        		monsterMail(MAIL_WEBMASTER, $subject, $mail);
			        	}else {
			        		echo $mail;
			        		monsterMail($email_mail, $subject, $mail);
			        		monsterMail(MAIL_WEBMASTER, $subject, $mail);
			        	}
	        	}
	        	else{
	        		$sss = $_SESSION['user_not_validate'];
	        		//$sss[$login] = time();
	        		$a = $sss[$login];
	        		if($a){
	        			if((time()-$a)>MAX_MINUTE_RESEND_MAIL_VALIDATION*60){
	        				$sss[$login] = time();
	        				$_SESSION['user_not_validate'] = $sss;
	        				if(STATUS_EMAIL == 0) {
			        			echo $mail;
				        	}elseif(STATUS_EMAIL == 1) {
				        		monsterMail($email_mail, $subject, $mail);
				        		monsterMail(MAIL_WEBMASTER, $subject, $mail);
				        	}else {
				        		echo $mail;
				        		monsterMail($email_mail, $subject, $mail);
				        		monsterMail(MAIL_WEBMASTER, $subject, $mail);
				        	}       				
	        			}
	        		}
	        		else{
	        			$sss[$login] = time();
	        			$_SESSION['user_not_validate'] = $sss;
	        			if(STATUS_EMAIL == 0) {
		        			echo $mail;
			        	}elseif(STATUS_EMAIL == 1) {
			        		monsterMail($email_mail, $subject, $mail);
			        		monsterMail(MAIL_WEBMASTER, $subject, $mail);
			        	}else {
			        		echo $mail;
			        		monsterMail($email_mail, $subject, $mail);
			        		monsterMail(MAIL_WEBMASTER, $subject, $mail);
			        	}
	        		}
	        	}
            modelUser::insertHisto(modelUser::TYPE_HISTO_ERROR, $login, md5($pass));
	            //throw new Exception('Vous devez d\'abord activer votre compte');
	            //$boo = true;
            	//Persistence::register(PERSIST_MESSAGE, new Message($xml['error_message_3'], Message::ERROR));
            	$oubli->showBlock('immposible');
                //echo 'Vous ne pouvez pas redemander le mot de passe d\'un compte pas encore activé';
            }
        }else {
           // message d'erreur
           Persistence::register(PERSIST_MESSAGE, new Message($xml['error_message_2'], Message::ERROR));
           $oubli->showBlock('formulaire');
           //echo 'cet email n\'existe pas';
        }
	}
    else {
       // message d'erreur
       Persistence::register(PERSIST_MESSAGE, new Message($xml['error_message_1'], Message::ERROR));
       $oubli->showBlock('formulaire');
       //echo 'email incorrecte';
    }
}
else {
    $oubli->setVariable('mail', (isset($_POST['mail_oubli']))?$_POST['mail_oubli']:'');
    $oubli->showBlock('formulaire');
}
//$oubli->setVariable('nom_page_title', $xml['main_title']);

$oubli->stop();
$page->setBody($oubli);

// affichage
$page->display();

?>